package linkedlist;

/**
 * @author 十八岁讨厌编程
 * @date 2025/6/27 21:09
 * @PROJECT_NAME leetcode
 * @description
 */

public class Solution707 {

    class MyLinkedList {
        int val;

        MyLinkedList next;

        int length;

        public MyLinkedList() {
            val = -1;
            next = null;
            length = 0;
        }

        public MyLinkedList(int val,MyLinkedList next) {
            this.val = val;
            this.next = next;
        }

        public int get(int index) {
            if(index >= length || index < 0) {
                return -1;
            }
            int count = index + 2;
            MyLinkedList pointer = this;
            while(count > 0) {
                if(count == 1) return pointer.val;
                count -= 1;
                pointer = pointer.next;
            }
            return -1;
        }

        public void addAtHead(int val) {
            MyLinkedList addNode = new MyLinkedList(val,this.next);
            this.next = addNode;
            length += 1;
        }

        public void addAtTail(int val) {
            MyLinkedList pointer = this;
            while(pointer.next != null) pointer = pointer.next;
            MyLinkedList addNode = new MyLinkedList(val,null);
            pointer.next = addNode;
            length += 1;
        }

        public void addAtIndex(int index, int val) {
            if(index > length || index < 0) {
                return;
            }else if(index == length) {
                addAtTail(val);
            }else if(index == 0){
                addAtHead(val);
            }else {
                int count = index + 1;
                MyLinkedList pointer = this;
                while(count > 0 && pointer.next != null) {
                    if(count == 1) {
                        MyLinkedList addNode = new MyLinkedList(val,pointer.next);
                        pointer.next = addNode;
                    }
                    count -= 1;
                    pointer = pointer.next;
                }
                length += 1;
            }
        }

        public void deleteAtIndex(int index) {
            if(index >= length || index < 0) {
                return;
            }else {
                int count = index + 1;
                MyLinkedList pointer = this;
                while(count > 0 && pointer.next != null) {
                    if(count == 1) {
                        pointer.next = pointer.next.next;
                    }
                    count -= 1;
                    pointer = pointer.next;
                }
                length -= 1;
            }
        }
    }

}
